// pages/details/details.js
var time = require('../../utils/time.js')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nicknameShow: false,
    userme: '',
    imageRoot: app.globalData.imageRoot,
    showAI: false,
    Interval: '', //获取用户浏览时间计时器
    Interval_num: 0,
    Interval_Time: '',
    currentTab: 0,
    color: 0,
    chek: 0,
    houseId: "",
    list: {},
    carousel: [{
      id: 1,
      url: 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg',
      img: 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg'
    }, {
      id: 2,
      url: 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg',
      img: 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg'
    }, {
      id: 3,
      url: 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg',
      img: 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg'
    }],
    markers: [{
      title: '',
      id: 0,
      latitude: '',
      longitude: '',
      width: 20,
      height: 25,
      iconPath: 'https://api.yipaiju.com/resources/images/wawa/dingwei.png'
    }],
    background: [{
      name: '地铁',
      text: '',
      url: ''
    },
    {
      name: '学校',
      text: '',
      url: ''
    }, {
      name: '医院',
      text: '',
      url: ''
    }, {
      name: '生活',
      text: '',
      url: ''
    }
    ],
    listings1: [{
      name: '小区',
      text: '',
    },
    {
      name: '户  型',
      text: ''
    },
    {
      name: '建筑面积',
      text: ''
    },
    {
      name: '出售价格',
      text: ''
    },
    {
      name: '楼层',
      text: ''
    },
    {
      name: '电梯',
      text: ''
    },
    {
      name: '朝向',
      text: ''
    },
    {
      name: '装修',
      text: ''
    },
    {
      name: '用途',
      text: ''
    },
    {
      name: '挂牌',
      text: ''
    },
    {
      name: '楼龄',
      text: ''
    },
    {
      name: '套内面积',
      text: ''
    }
    ],
    listings2: [{
      name: '小区',
      text: ''
    },
    {
      name: '楼 层',
      text: ''
    },
    {
      name: '用 途',
      text: ''
    },
    {
      name: '保 证 金',
      text: ''
    },
    {
      name: '交付情况',
      text: ''
    },
    {
      name: '增价幅度',
      text: ''
    },
    {
      name: '看房详情',
      text: ''
    },
    ],
    zz: [{
      name: '登记时间',
      text: ''
    },
    {
      name: '是否唯一',
      text: ''
    },
    {
      name: '共有情况',
      text: ''
    },
    {
      name: '附属学位',
      text: ''
    },
    {
      name: '是否占用',
      text: ''
    },
    ],
    zy: [{
      name: '小  区',
      text: '金海御苑'
    },
    {
      name: '楼 层',
      text: '22层'
    },
    {
      name: '用 途',
      text: '普通住宅'
    },
    {
      name: '租赁合同',
      img: ['https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/yqbg.png', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg']
    }
    ],
    cq: [{
      name: '抵押单位',
      text: '',
      index: 0
    },
    {
      name: '抵押金额',
      text: '',
      index: 1
    },
    {
      name: '抵押权人',
      text: '',
      index: 2
    },
    {
      name: '抵押金额',
      text: '',
      index: 3
    },
    {
      name: '查封情况',
      text: '',
      index: 4
    },
    {
      name: '查封单位',
      text: '',
      index: 5
    },
    {
      name: '查封金额',
      text: '',
      index: 6
    },
    {
      name: '查封单位',
      text: '',
      index: 7
    },
    {
      name: '查封金额',
      text: '',
      index: 8
    },
    {
      name: '房产证件',
      img: ['https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg'],
      index: 9
    },
    {
      name: '购房发票',
      img: ['https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg'],
      index: 10
    },
    {
      name: '房产查册',
      img: ['https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg'],
      index: 11
    },
    {
      name: '判决文书',
      img: ['https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg'],
      index: 12
    },
    ],
    qt: [{
      name: '放盘底价',
      text: '',
      index: 0
    },
    {
      name: '推荐人员',
      text: '',
      index: 1
    },
    {
      name: '需求信息',
      text: '',
      index: 2
    },
    {
      name: '评估报告',
      img: ['https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg'],
      index: 3
    },
    {
      name: '独家协议',
      img: ['https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg', 'https://api.yipaiju.com/resources/images/wawa/index_1.jpg'],
      index: 4
    },
    ],
    lists: [],
    active: 0,
    chek: 0,
    admin: 1,
    btnText: '开盘通知',
    status: 0,
    index: '',
    carousel_index: 1,
    recommend: [],
    favor_id: '',
    userId: '', //自身id
    phone: true
  },
  navTo(e) {
    var url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url,
    })
  },
  goToChat() {
    wx.navigateTo({
      url: '../../subpackages/pages/chat/chat?id=' + this.data.houseId + '&status=' + this.data.status + '&autoSendMsg=true',
    });
  },
  openLocation: function (e) {
    var that = this;
    var value = e.detail.value
    var list = that.data.list;
    wx.openLocation({
      longitude: Number(list.longitude),
      latitude: Number(list.latitude),
      // longitude: list.longitude,
      // latitude: list.latitude,
      name: list.residentialQuarterName,
      address: list.address
    })
  },
  getPhoneNumber(e) { //页面授权电话
    // console.log(e)
    let that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      let data = {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        appid: app.globalData.appid,
      }
      app.ports.api54({
        data
      }).then((res) => {
        that.data.user.phone_is_verified = true
        that.setData({
          phone: false,
          user: that.data.user
        })
      }).catch(() => {
        console.error("授权电话号码解密失败！")
      })
    } else {
      return
    }
  },
  formatRegdesc(data) { //详情，对多种情景进行处理
    return data;
    data = data.replace(/\<img/gi, '<img class="rich-img" '); //对图片进行格式化
    data = data.replace(/\<div/gi, '<div class="rich-div" '); //给盒子进行格式化
    data = data.replace(/\<p/gi, '<P class="rich-pdesc" '); //对段落进行格式化
    data = data.replace(/\<span style=/gi, '<SPAN style="font-size:26rpx;" '); //对style进行格式化
    data = data.replace(/\enforce/gi, '<P style="display: none;" '); //对非法字符进行格式化
    data = data.replace(/\null/gi, '<P style="display: none;" '); //对空白字符进行格式化
    return data
  },
  formatReg(data) { //格式化富文本，公告、须知不含有图片只有文本
    return data;
    data = data.replace(/\<p/gi, '<P class="rich-p" '); //对段落进行格式化
    data = data.replace(/\enforce/gi, '<P style="display: none;" '); //对非法字符进行格式化
    data = data.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, 'style="width:100%;height:auto;margin:auto;"'); //对文本清楚所有样式

    data = data.replace(/<\/div>/ig, '\r\n');
    data = data.replace(/<\/li>/ig, '\r\n');
    data = data.replace(/<li>/ig, '  *  ');
    data = data.replace(/<\/ul>/ig, '\r\n');
    //-- remove BR tags and replace them with line break
    data = data.replace(/<br\s*[\/]?>/gi, "\r\n");

    //-- remove P and A tags but preserve what's inside of them
    data = data.replace(/<p.*?>/gi, "\r\n");
    data = data.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 ($1)");

    //-- remove all inside SCRIPT and STYLE tags
    data = data.replace(/<script.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/script>/gi, "");
    data = data.replace(/<style.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/style>/gi, "");
    //-- remove all else
    data = data.replace(/<(?:.|\s)*?>/g, "");

    //-- get rid of more than 2 multiple line breaks:
    data = data.replace(/(?:(?:\r\n|\r|\n)\s*){2,}/gim, "\r\n\r\n");

    //-- get rid of more than 2 spaces:
    data = data.replace(/ +(?= )/g, '');

    //-- get rid of html-encoded characters:
    data = data.replace(/ /gi, " ");
    data = data.replace(/&/gi, "&");
    data = data.replace(/"/gi, '"');
    data = data.replace(/</gi, '<');
    data = data.replace(/>/gi, '>');
    data = data.replace('&ldquo;', '')
    data = data.replace('&rdquo;', '')
    data = data.replace(/\&.*?\;/g, '');// 去掉转义字符


    return data
  },
  api(data) {
    var that = this;
    // if (that.data.options.share || that.data.options.scene) that.share(that.data.options)

    // 需要打开的
    wx.showLoading({
      title: '加载中',
    })
    var admin = that.data.admin
    var data = {}
    data.id = that.data.id;
    var status = that.data.status;
    app.globalData.indexUrl = this;
    var arr = [0, 2, 3]
    if (status == 0) {
      if (arr.includes(admin)) {
        getApp().ports.fpxqAdmin({
          data: data
        }).then((res) => {
          var res = res.data;
          getApp().ports.img({
            data: {
              relatedObjectId: res.nameMd5
            }
          }).then((obj) => {
            var obj = obj.data;
            that.setData({
              carousel: obj.banner
            })
          }).catch(() => { });
          that.data.markers[0].title = res.address;
          that.data.markers[0].latitude = res.latitude;
          that.data.markers[0].longitude = res.longitude;
          res.time = (app.timeFormat(res.startTime) || '') + '-' + (app.timeFormat(res.endTime) || '')
          if (res.status == '已完成') {
            res.priceYuan = res.dealPrice
          }
          if (res.status == '已流拍') res.status = '已结束'
          if (res.isfavor == 1) { }
          that.data.background[0].text = res.traffic;
          that.data.background[1].text = res.education;
          that.data.background[2].text = res.hospital;
          that.data.background[3].text = res.amenity;
          switch (res.stage) {
            case '变卖':
              res.stage = '秒杀'
              break;
            case '一拍':
              res.stage = '一轮'
              break;
            case '二拍':
              res.stage = '二轮'
              break;
          }
          res.tags = [{
            name: res.builtUpAreaSquareCentimeter + '㎡'
          }, {
            name: res.discountRate + '折'
          }, {
            name: res.stage
          }]
          res.marketPriceYuan = Math.floor((res.marketPriceYuan / 10000));
          res.dealPrice = Math.floor((res.dealPrice / 10000));
          res.estimatePriceYuan = Math.floor((res.estimatePriceYuan / 10000));
          res.priceYuan = Math.floor((res.priceYuan / 10000));
          res.sf = Math.floor(res.priceYuan * 0.3);
          //利用正则格式化富文本
          res.description = that.formatRegdesc(res.description);
          res.announcement = that.formatReg(res.announcement);
          res.notice = that.formatReg(res.notice);
          Object.assign(that.data, {
            favor_id: res.favorId,
            notice_id: res.noticeId,
          })
          that.setData({
            list: res,
            background: that.data.background,
            markers: that.data.markers,
          })
          that.setList(res)
          wx.hideLoading({
            success: (res) => { },
          })
        }).catch((e) => {
          console.error('出啥错了？', e);
        });
      } else {
        getApp().ports.fpxq({
          data: data
        }).then((res) => {
          var res = res.data;
          getApp().ports.img({
            data: {
              relatedObjectId: res.nameMd5
            }
          }).then((obj) => {
            var obj = obj.data;
            that.setData({
              carousel: obj.banner
            })
          }).catch(() => { });
          that.data.markers[0].title = res.address;
          that.data.markers[0].latitude = res.latitude;
          that.data.markers[0].longitude = res.longitude;
          res.time = (app.timeFormat(res.startTime) || '') + '-' + (app.timeFormat(res.endTime) || '')
          that.data.background[0].text = res.traffic;
          that.data.background[1].text = res.education;
          that.data.background[2].text = res.hospital;
          that.data.background[3].text = res.amenity;
          res.priceYuan = Math.floor((res.priceYuan / 10000));
          res.dealPrice = Math.floor((res.dealPrice / 10000));
          res.marketPriceYuan = Math.floor((res.marketPriceYuan / 10000));
          res.estimatePriceYuan = Math.floor((res.estimatePriceYuan / 10000));
          switch (res.stage) {
            case '变卖':
              res.stage = '秒杀'
              break;
            case '一拍':
              res.stage = '一轮'
              break;
            case '二拍':
              res.stage = '二轮'
              break;
          }
          res.tags = [{
            name: res.builtUpAreaSquareCentimeter + '㎡'
          }, {
            name: res.discountRate + '折'
          }, {
            name: res.stage
          }]
          res.sf = Math.floor(res.priceYuan * 0.3);
          res.yg = res.priceYuan / 0.7;
          var statuss = ['待审核', '待上架', '出售中', '已出售'];
          res.stage = statuss[res.stage]
          //利用正则格式化富文本
          res.description = that.formatRegdesc(res.description);
          res.announcement = that.formatReg(res.announcement);
          res.notice = that.formatReg(res.notice);
          that.setData({
            list: res,
            background: that.data.background,
            markers: that.data.markers
          })
          Object.assign(that.data, {
            favor_id: res.favorId,
            notice_id: res.noticeId,
          })
          that.setList(res)
          wx.hideLoading({
            success: (res) => { },
          })
        }).catch(() => {
          console.error('出啥错了？');
        });
      }
    } else {
      // var statuss = ['', '出售中', '已出售'];
      if (arr.includes(admin)) {
        getApp().ports.zkxqAdmin({
          data: data
        }).then((res) => {
          var res = res.data;
          getApp().ports.img({
            data: {
              relatedObjectId: res.id
            }
          }).then((obj) => {
            var obj = obj.data;
            that.data.zy[3].img = obj.lease_contract
            that.data.cq[9].img = obj.estate_license
            that.data.cq[10].img = obj.invoice
            that.data.cq[11].img = obj.house_property
            that.data.cq[12].img = obj.judgment_doc
            that.data.qt[3].img = obj.assessment_report
            that.data.qt[4].img = obj.exclusive_agreement

            if (obj.banner) {
              obj.banner.forEach(item => {
                item.url = that.data.imageRoot + item.url;
              })
            }
            that.setData({
              carousel: obj.banner,
              zy: that.data.zy,
              cq: that.data.cq,
              qt: that.data.qt,
            })
          }).catch(() => { })
          var statuss = ['待审核', '待上架', '出售中', '已出售'];
          that.data.markers[0].title = res.title;
          that.data.markers[0].latitude = res.latitude;
          that.data.markers[0].longitude = res.longitude;
          res.status = statuss[res.status]

          that.data.background[0].text = res.traffic;
          that.data.background[1].text = res.education;
          that.data.background[2].text = res.hospital;
          that.data.background[3].text = res.amenity;
          res.time = res.uploadTime

          // res.market_price_yuan = Math.floor((res.market_price_yuan / 10000));
          // res.estimate_price_yuan = Math.floor((res.estimate_price_yuan / 10000));
          // res.price_yuan = Math.floor((res.price_yuan / 10000));
          res.sf = Math.floor(res.priceYuan * 0.3);

          // res.status = statuss[res.status]
          res.tags = [];
          res.tags.push({
            name: res.builtUpAreaSquareCentimeter + '㎡'
          })

          console.log(that.data.markers[0], "===============================1111222")

          Object.assign(that.data, {
            favor_id: res.favorId,
            notice_id: res.noticeId,
          })
          that.setData({
            list: res,
            background: that.data.background,
            markers: that.data.markers,
          })
          that.setList(res)
          wx.hideLoading({
            success: (res) => { },
          })
        }).catch(() => {
          console.error('出啥错了？');
        });
      } else if (admin == 1) {

        getApp().ports.zkxq({
          data: data
        }).then((res) => {
          var res = res.data;
          getApp().ports.img({
            data: {
              relatedObjectId: res.id
            }
          }).then((obj) => {
            var obj = obj.data;
            var bannerImgs = [];
            if (obj.banner) {
              obj.banner.forEach(item => {
                item.url = that.data.imageRoot + item.url;
              })
            }
            that.setData({
              carousel: obj.banner,
            })
          }).catch(() => { })
          that.data.background[0].text = res.traffic;
          that.data.background[1].text = res.education;
          that.data.background[2].text = res.hospital;
          that.data.background[3].text = res.amenity;
          res.time = res.uploadTime
          var statuss = ['待审核', '待上架', '出售中', '已出售'];
          that.data.markers[0].title = res.title;
          that.data.markers[0].latitude = res.latitude;
          that.data.markers[0].longitude = res.longitude;
          res.status = statuss[res.status]
          console.log(that.data.markers[0])
          res.sf = Math.floor(res.priceYuan * 0.3);
          // res.market_price_yuan = Math.floor((res.market_price_yuan / 10000));
          // res.estimate_price_yuan = Math.floor((res.estimate_price_yuan / 10000));
          // res.price_yuan = Math.floor((res.price_yuan / 10000));
          res.tags.push({
            name: res.builtUpAreaSquareCentimeter + '㎡'
          })
          that.setData({
            list: res,
            background: that.data.background,
            favor_id: res.favorId,
            notice_id: res.noticeId,
            markers: that.data.markers
          })
          that.setList(res)
          wx.hideLoading({
            success: (res) => { },
          })
        }).catch(() => {
          console.error('出啥错了？');
        });
      } else {
        wx.showToast({
          title: `不明类型 status=${status}`,
          icon: 'none'
        })
        wx.hideLoading({
          success: (res) => { },
        })
      }
    }
  },
  fqjd() {
    var that = this;
    var data = {
      "status": 0,
      "stage": 0,
      "foreclosedHouseId": that.data.id
    }
    wx.showModal({
      title: '尽职调查预约',
      content: '即刻查看房源详尽信息',
      success(res) {
        if (res.confirm) {
          if (that.data.user.phone_is_verified) {
            getApp().ports.fqjd({
              data: data
            }).then((res) => {
              var res = res.data;
              wx.showToast({
                title: '发起尽调预约成功',
                icon: 'none'
              })
            }).catch(() => {
              console.error('出啥错了？');
            });
          } else {
            wx.showModal({
              title: '请先授权获取手机号',
              icon: 'none'
            })
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  setList(res) {
    var that = this;
    var status = that.data.status;
    var admin = that.data.admin;
    console.log('房源信息', res);
    that.setData({
      houseId: res.id
    })
    console.log('房子id', that.data.houseId);
    if (status === 0) {
      console.log('法拍')
      var listings2 = that.data.listings2;
      listings2[0].text = res.residentialQuarterName;
      listings2[1].text = (res.houseLevel == 0) ? '暂无信息' : res.houseLevel;
      listings2[2].text = res.houseType;
      listings2[3].text = res.depositYuan;
      listings2[4].text = '咨询交付';
      listings2[5].text = res.increasePriceYuan;
      listings2[6].text = '预约看样';
      if (admin == 0 && admin != 3) {
        console.log('admin==0')
        listings2.push({
          name: '房屋来源',
          text: res.origin
        }, {
          name: '处置单位',
          text: res.court
        }, {
          name: '咨询电话',
          text: res.phone
        })
      }
      console.log(listings2)
      that.setData({
        listings2: listings2
      })
    } else {
      var zz = that.data.zz;
      var zy = that.data.zy;
      var cq = that.data.cq;
      var qt = that.data.qt;
      var listings1 = that.data.listings1;
      // var listings1 = [{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}];
      listings1[0].text = res.residentialQuarterName;
      listings1[1].text = res.bedroom + '房' + res.livingroom + '厅';
      listings1[2].text = res.builtUpAreaSquareCentimeter; //建筑面积
      listings1[3].text = res.priceYuan;
      if (Math.floor((res.houseTotalLevel / 2)) - 2 > res.houseLevel) {
        listings1[4].text = '低楼层';
      } else if ((Math.floor((res.houseTotalLevel / 2)) - 2) <= res.houseLevel && (Math.floor((res.houseTotalLevel / 2)) + 2) >= res.houseLevel) {
        listings1[4].text = '中楼层';
      } else if (Math.floor((res.houseTotalLevel / 2)) + 2 < res.houseLevel) {
        listings1[4].text = '高楼层';
      } else {
        listings1[4].text = '暂无信息';
      }
      // listings1[4].text = res.house_level;
      listings1[5].text = res.elevator;
      listings1[6].text = res.orientation;
      listings1[7].text = res.decoration; //装修
      listings1[8].text = '住宅用房'; //用途
      listings1[9].text = res.uploadTime; //挂牌
      listings1[10].text = res.houseAge; //楼龄
      listings1[11].text = res.insideAreaSquareCentimeter; //套内面积
      if (admin == 0) {
        var obj = [{}, {}, {}, {}, {}]
        obj[0].name = '房产地址';
        obj[1].name = '单元坐落';
        obj[2].name = '看房电话';
        obj[3].name = '当前楼层';
        obj[4].name = '总楼层';
        obj[0].text = res.province + res.city + res.district;
        obj[1].text = res.location + " " + res.unitNo; //单元坐落
        obj[2].text = res.phone; //看房电话
        obj[3].text = res.houseLevel;
        obj[4].text = res.houseTotalLevel;
        obj.forEach(item => {
          listings1.push(item)
        })
        // for (var i = 0; i < obj.length; i++) {
        //   listings1.push(obj[i])
        // }
      }
      zz[0].text = res.registerTime;
      zz[1].text = res.onlyHouse;
      zz[2].text = res.owningType;
      zz[3].text = res.degree;
      zz[4].text = res.havingDegree;
      zy[0].text = res.residentialQuarterName;
      zy[1].text = res.houseTotalLevel;
      cq[0].text = res.mortgage1;
      cq[1].text = res.mortgage1PriceYuan;
      if (res.mortgage2) cq[2].text = res.mortgage2;
      if (res.mortgage2PriceYuan) cq[3].text = res.mortgage2PriceYuan;
      cq[4].text = res.seizure;
      cq[5].text = res.confiscator1;
      cq[6].text = res.seizureAmount1;
      qt[0].text = res.intentionPriceYuan
      qt[1].text = res.recommender;
      qt[2].text = res.specificRequirement;
      if (res.confiscator2) cq[7].text = res.confiscator2;
      if (res.seizureAmount2) cq[8].text = res.seizureAmount2;
      that.setData({
        listings1: listings1,
        zz: zz,
        zy: zy,
        cq: cq,
        qt: qt
      })
    }
  },
  bindRegionChange(e) { },
  setListings() {
    var that = this;
    var data = {
      page_size: 10,
    };
    console.log(that.data.list)
    if (that.data.list.longitude || that.data.list.latitude) {
      data.longitude = that.data.list.longitude
      data.latitude = that.data.list.latitude
    } else {
      data.longitude = app.globalData.longitude
      data.latitude = app.globalData.latitude
    }
    var statuss = ['待审核', '待上架', '出售中', '已出售'];
    getApp().ports.apiqb({
      data: data
    }).then((res) => {
      var res = res.data;
      res.forEach(item => {
        if (item.type == 1) {
          switch (item.stage) {
            case '变卖':
              item.stage = '秒杀'
              break;
            case '一拍':
              item.stage = '一轮'
              break;
            case '二拍':
              item.stage = '二轮'
              break;
          }
          item.tags = [{
            name: item.builtUpAreaSquareCentimeter + '㎡'
          }, {
            name: item.discountRate + '折'
          }, {
            name: item.stage
          }]
          item.time = (app.timeFormat(item.startTime) || '') + '-' + (app.timeFormat(item.endTime) || '')
          item.marketPriceYuan = Math.floor((item.marketPriceYuan / 10000));
          item.priceYuan = Math.floor((item.priceYuan / 10000));
          item.estimatePriceYuan = Math.floor((item.estimatePriceYuan / 10000));
          item.url = "../details/details?status=0&&id=" + item.id
        } else {
          item.time = item.uploadTime;
          item.status = statuss[parseInt(item.status)];
          if (item.tagsstr) {
            let tags = [];
            item.tagsstr.split(",").forEach(item => {
              tags.push({ name: item })
            })
            item.tags = tags;
          }
          item.url = "../details/details?status=1&&id=" + item.id
        }
      })
      that.setData({
        recommend: res
      })
    }).catch(() => {
      console.error('出啥错了？');
    });
  },
  login(data) {
    var phone;
    getApp().ports.getInfo({}).then((res) => {
      phone = (res.data.phone_is_verified ? false : true)
      this.setData({
        login: app.globalData.login,
        phone: phone
      })
    }).catch(() => {
      console.error("获取自身信息出错！")
    })
  },

  getPriceConfig() {
    var that = this;
    getApp().ports.getPriceConfig({
      data: { configKey: 'review.show' }
    }).then((res) => {
      var showAI = res.msg === 'true';
      that.setData({
        showAI: showAI
      });
    }).catch((error) => {

    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    console.log("onload>>>>>", options);

    var that = this;
    var status = Number(options.status)
    let partnership = ['合伙专员', '合伙经理']
    await getApp().ports.api30().then(async (res) => {
      var res = res.data;
      if (res.active_role) {

        console.log(res.active_role.title)
        if (res.active_role.title != "合伙专员" && res.active_role.title != "合伙经理") {
          that.data.admin = 0
        } else if (partnership.includes(res.active_role.title)) {
          that.data.admin = 3
        }
      } else {
        console.log(' 无身份')
        that.data.admin = (res.is_verified ? 2 : 1)
        // if(res.is_verified){
        //   that.data.admin = 2
        // }else{
        //   that.data.admin = 1
        // }
      }
      Object.assign(that.data, {
        user: res
      })
      that.setData({
        id: options.id,
        admin: that.data.admin,
        status: status,
        barH: app.globalData.system.barH + 5,
      })
    })

    if (options.scene || options.share) {
      await that.share(options)
    }
    var btnText;
    btnText = (status === 0 ? "开盘通知" : "降价提醒")
    // if (status === 0) {
    //   btnText = "开盘通知"
    // } else {
    //   btnText = "降价提醒"
    // }
    that.setData({
      btnText: btnText,
    })
    that.api({});
    that.userme();
    that.getPriceConfig(); // 获取价格配置，判断是否显示AI按钮
    // that.onButtonClick('onload')
  },
  // onButtonClick  (status) {
  //   const actions = new Map([
  //     ['li', ['processing', 'IndexPage']],
  //     ['onload', ['fail', 'FailPage111']],
  //     [3, ['fail', 'FailPage']],
  //     [4, ['success', '*']],
  //     [5, ['cancel', 'CancelPage']],
  //     ['default', ['other', 'Index']],
  //   ])
  //   let action = actions.get(status) || actions.get('default')
  //   console.log(action[0])
  //   console.log(action[1])
  // },
  async share(options) {
    var that = this;
    if (options.scene) { //扫码进入
      // options.scene 格式应该是 userId=3&id=551&status=0

      let params = {};
      decodeURIComponent(options.scene).split("&").forEach(item => {
        let itemParam = item.split("=");
        params[itemParam[0]] = itemParam[1];
      })
      // 邀请id
      let invitestId = params.userId;
      let data = {
        user_pk: invitestId
      }
      that.setData({
        id: params.id,
        status: params.status,
        active: 0
      })
      that.login(true)  // 不需要了 还是需要
      app.ports.apiinvites({
        data
      }).then().catch(() => {
        console.error('建立邀请关系失败！')
      })

      // let parms = {
      //   key: options.scene
      // }
      // // TODO 这个接口不需要了  直接从scene中获取
      // await app.ports.apiqrdata({
      //   parms
      // }).then(async (res) => {
      //   let res_data = JSON.parse(res.data)
      //   // 邀请id
      //   let invitestId = res_data.userId
      //   let data = {
      //     user_pk: invitestId
      //   }
      //   that.setData({
      //     id: res_data.id,
      //     status: res_data.status,
      //     active: 0
      //   })
      //   that.login(true)
      //   app.ports.apiinvites({
      //     data
      //   }).then().catch(() => {
      //     console.error('建立邀请关系失败！')
      //   })
      // }).catch(() => {
      //   console.error('拉取启动参数！')
      // })
    }
    if (options.share) { //分享进入页面
      let shareId = options.share
      let data = {
        user_pk: shareId
      }
      app.ports.apiinvites({
        data
      }).then(res => {
        that.setData({
          status: Number(options.status),
          id: options.id,
          active: 0
        })
        that.login(true)   //  不需要了  还是需要 因为要判断电话号
      }).catch(() => {
        console.error('建立邀请关系失败！')
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.setListings()
    that.data.Interval = setInterval(function () { //获取用户在页面停留时间
      that.data.Interval_Time = time.IntervalTime(null, 0)
      that.data.Interval_num += 1;
      Object.assign(that.data, {
        Interval: that.data.Interval,
        Interval_num: that.data.Interval_num,
        Interval_Time: that.data.Interval_Time
      })
    }, 1000)
    that.login()
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    clearInterval(that.data.Interval)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    var user = that.data.user;
    var data = {
      "userId": wx.getStorageSync('userId'),
      "userNickname": user.nickname,
      "houseId": that.data.id,
      "houseTitle": that.data.list.title,
      "houseCommunity": that.data.list.residential_quarter_name,
      // "houseCategory": (that.data.status == 0 ? '优选' : '折扣'),
      "houseCategory": (that.data.status == 0 ? '1' : '2'),
      "accessTime": that.data.Interval_Time,
      "accessIntervalSeconds": that.data.Interval_num,
    }
    console.log(data, "==================>>getHistory")
    clearInterval(that.data.Interval)
    getApp().ports.getHistory({
      data
    }).then(res => {
      console.log(res.data)
    }).catch(() => {
      console.error('获取用户浏览记录失败')
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: async function () {
    let that = this;
    let shareId = wx.getStorageSync('userId')
    console.log("share action1111>>>>>", shareId, that.data.status, that.data.id)

    return {
      title: that.data.list.title,
      path: 'pages/details/details?userId=' + shareId + '&share=' + shareId + '&status=' + that.data.status + '&id=' + that.data.id + '&abc=' + shareId,
      success: function (res) { }
    }

  },
  swiperChange(e) {
    var that = this;
    that.setData({
      carousel_index: e.detail.current + 1
    })
  },
  item_swiper: function (e) {
    var that = this;
    that.setData({
      chek: e.detail.current
    })
  },
  banner_preview(e) {
    var that = this;
    var banner = that.data.carousel;
    var index = that.data.carousel_index - 1;
    var img = [];
    banner.forEach(item => {
      img.push(item.url)
    })
    wx.previewImage({
      //当前显示图片
      current: img[index],
      //所有图片
      urls: img
    })
  },
  previewImg: function (e) {
    var that = this;
    var Imgs = [];
    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.index;
    var type = e.currentTarget.dataset.type;
    if (status == 'zy') {
      that.data.zy[3].img.forEach(item => {
        Imgs.push(item.url)
      })
    }
    if (status == 'cq') {
      that.data.cq[type].img.forEach(item => {
        Imgs.push(item.url)
      })
    }
    if (status == 'qt') {
      that.data.qt[type].img.forEach(item => {
        Imgs.push(item.url)
      })
      // for (let i in that.data.qt[type].img) {
      //   Imgs.push(that.data.qt[type].img[i].url)
      // }
    }
    wx.previewImage({
      //当前显示图片
      current: Imgs[index].url,
      //所有图片
      urls: Imgs
    })
  },
  tabChange(e) {
    this.setData({
      active: e.detail.index
    })
  },
  phoneCall(e) {
    wx.makePhoneCall({
      phoneNumber: app.globalData.phone
    })
  },
  onClickButton(e) {
    var that = this;
    if (that.data.status == 0) {
      getApp().ports.yjyy({
        data: {
          "status": 1,
          "stage": 1,
          "foreclosedHouseId": that.data.id,
          "rate": 0,
          "comment": "string"
        }
      }).then((res) => {
        var res = res.data;
        wx.showToast({
          title: '预约成功',
          icon: 'none'
        })
      }).catch(() => {
        console.error('出啥错了？');
      });
    } else {
      getApp().ports.zkyj({
        data: {
          "status": 1,
          "stage": 1,
          "discountHouseId": that.data.id,
          "rate": 0,
          "comment": "string"
        }
      }).then((res) => {
        var res = res.data;
        wx.showToast({
          title: '预约成功',
          icon: 'none'
        })
      }).catch(() => {
        console.error('出啥错了？');
      });
    }
  },
  collection(e) { //收藏
    var that = this;
    var data = {};
    if (that.data.status == 0) {
      data.foreclosedHouseId = that.data.id
    } else {
      data.discountHouseId = that.data.id
    }

    if (that.data.list.isfavor == 0) {
      getApp().ports.collection({
        data: data
      }).then((res) => {
        var res = res.data;
        wx.showToast({
          title: '收藏成功',
          icon: 'none'
        })
        that.setData({
          favor_id: res.id
        })
      }).catch(() => {
        console.error('出啥错了？');
      });
    } else {
      // return
      getApp().ports.qxcollection({
        id: that.data.favor_id
      }).then((res) => {
        var res = res.data;
        wx.showToast({
          title: '取消收藏成功',
          icon: 'none'
        })

      }).catch(() => {
        console.error('出啥错了？');
      });
    }
    that.data.list.isfavor = !that.data.list.isfavor
    that.setData({
      list: that.data.list
    })
  },
  goToChatNoAuto() {
    wx.navigateTo({
      url: '../../subpackages/pages/chat/chat?id=' + this.data.houseId + '&status=' + this.data.status + '&noAuto=1',
    });
  },
  news(e) { //消息通知
    var that = this;
    var data = {};

    if (that.data.status == 0) {
      data.foreclosedHouseId = that.data.id
    } else {
      data.discountHouseId = that.data.id
    }
    if (that.data.list.isnotice == 0) {
      let tmplId = '';
      if (that.data.status == 0) {
        tmplId = 'vSOq9kLt2wrI_Z7pCRHbg5cgCB99HcMK8TdSd89LAm0'
      } else {
        tmplId = 'xrGDaKPb7-2Ia_GZQNwQlAU1Bl7M9pz2SeOy6LwpnPM'
      }
      wx.requestSubscribeMessage({
        tmplIds: [tmplId],
        success: function (res) {
          console.log(res, "订阅回调")
          if (res[tmplId] == 'accept') {
            getApp().ports.news({
              data: data
            }).then((res) => {
              var res = res.data;
              wx.showToast({
                title: '设置提醒成功',
                icon: 'none'
              })
              Object.assign(that.data, {
                notice_id: res.id
              })
              that.data.list.isnotice = !that.data.list.isnotice
              that.setData({
                list: that.data.list
              })
            }).catch(() => {
              console.error('出啥错了？');
            });
          }
        }
      })
    } else {
      getApp().ports.qxnews({
        id: that.data.notice_id
      }).then((res) => {
        var res = res.data;
        wx.showToast({
          title: '取消提醒成功',
          icon: 'none'
        })
        that.data.list.isnotice = !that.data.list.isnotice
        that.setData({
          list: that.data.list
        })
      }).catch(() => {
        console.error('出啥错了？');
      });
    }

  },
  navBack: function (e) {
    wx.navigateBack({
      delta: 1
    })
  },
  reLaunch(e) {
    wx.reLaunch({
      url: '../index/index',
    })
  },
  onShareTimeline() {

  },
  userme() {
    let that = this;
    getApp().ports.getInfo({}).then(res => {
      if (!res.data.nickname) {
        that.showNicknameDialog();
      }
      that.setData({
        userme: res.data
      })
    })
  },

  showNicknameDialog() {
    this.setData({
      nicknameShow: true
    })
  },

  onClickHide() {
    this.setData({
      nicknameShow: false
    });
  },

  nameInput(e) {
    this.data.userme.nickname = e.detail.value
    this.setData({
      userme: this.data.userme
    })
  },

  onChooseAvatar(e) {
    let that = this;
    const {
      avatarUrl
    } = e.detail
    wx.uploadFile({
      url: getApp().ports.upload,
      filePath: avatarUrl,
      name: 'file',
      formData: {
        'user': 'test'
      },
      success(res) {
        let data = JSON.parse(res.data)
        if (data.code == 200) {
          that.data.userme.avatar = data.url
          that.setData({
            userme: that.data.userme
          })
        }
      }
    })
  },

  modifyUserme() {
    let that = this;
    let data = {
      nickname: that.data.userme.nickname,
      avatar: that.data.userme.avatar,
      name: that.data.userme.name,
      card: that.data.userme.card
    }
    getApp().ports.apiUpdata({
      data
    }).then(res => {
      if (res.code == 200) {
        wx.showToast({
          title: '保存成功',
        })
        that.setData({
          nicknameShow: false
        })
      } else {
        wx.showToast({
          title: '网络错误',
          icon: 'error'
        })
      }
    })
  }
})